import React from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as serviceActionCreator from '../../actions/service-actions';
import {formatDate, getRealSize, Touchable} from '../../utils';
import ThemeStyles from '../../styles';
import ProgressBar from '../../components/progress-bar';
import _ from 'lodash';
import BottomSheet, {BottomSheetFlatList} from '@gorhom/bottom-sheet';
import SheetHead from '../../components/items/sheet-head';
import {FlatList} from 'react-native-gesture-handler';
import Separator from '../../components/separator';
import {I18n} from '../../reducers/intl';

class ServiceScreen extends React.PureComponent {
  static navigationOptions = ({navigation}) => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.service'),
    headerRight: () => (
      <Touchable onPress={() => navigation.navigate('ServiceRecord')}>
        <View
          style={[ThemeStyles.Layout.base.padding, {height: getRealSize(48)}]}>
          <Text
            style={[
              ThemeStyles.Front.base,
              ThemeStyles.Color.primary,
              {textAlign: 'right'},
            ]}>
            {I18n.t('page.title.serviceRecord')}
          </Text>
        </View>
      </Touchable>
    ),
  });

  state = {
    sheetIndex: -1,
  };

  componentDidMount() {
    const {user, serviceActions} = this.props;
    serviceActions.loadServices(user.plan.id);
  }

  render() {
    const {user, serviceActions, serviceState, navigation} = this.props;
    const serviceData = _.get(serviceState, 'serviceData', {});
    const data = Object.values(serviceData);
    const occupied = Math.ceil(Number(user.occupied) * 1024);
    const percent = Number(user.occupied) / user.plan.space;
    let renew = [];
    if (this.state.service) {
      renew = serviceData[this.state.service.id].renew;
    }
    return (
      <View style={{flex: 1}}>
        <FlatList
          data={data}
          keyExtractor={item => item.id}
          ItemSeparatorComponent={() => <Separator />}
          ListHeaderComponent={() => (
            <ProgressBar
              progress={percent}
              title={I18n.t('form.label.currentSpace')}
              total={`${_.get(user, 'plan.space', 0)}G`}
              current={`${occupied}M`}
            />
          )}
          renderItem={({item}) => (
            <ServiceCard
              title={item.name}
              max={item.order_limit}
              space={item.space}
              price={item.price}
              currentPlan={user.plan}
              service={item}
              validity={user.validity}
              showModalUpgrade={() => {
                // serviceActions.checkout(user.plan, this.state.service, item);
                // navigation.navigate('Checkout');
              }}
              showModalAmend={() => {
                this.setState(
                  {
                    service: item,
                    sheetIndex: 1,
                  },
                  () => {
                    serviceActions.loadRenew(user.plan, item, item);
                    this.BottomSheet.snapTo(1);
                  },
                );
              }}
            />
          )}
        />
        <BottomSheet
          ref={ref => {
            this.BottomSheet = ref;
          }}
          index={-1}
          style={Styles.sheetContainer}
          handleComponent={() => (
            <SheetHead onClose={() => this.BottomSheet.close()} />
          )}
          snapPoints={[-1, 400]}>
          <BottomSheetFlatList
            data={renew}
            keyExtractor={(_, index) => index}
            ItemSeparatorComponent={() => <Separator />}
            renderItem={({item}) => (
              <Touchable
                onPress={() => {
                  this.BottomSheet.close();
                  // serviceActions.checkout(user.plan, this.state.service, item);
                  // navigation.navigate('Checkout');
                }}>
                <View style={Styles.box}>
                  <View style={Styles.head}>
                    <Text style={Styles.title}>
                      {I18n.t('form.label.month', {month: item.month})}
                    </Text>
                    <Text style={Styles.name}>￥{item.amt}</Text>
                  </View>
                  <View style={Styles.content}>
                    <Text style={Styles.label}>
                      {I18n.t('form.label.charge', {
                        result: item.amt / item.month,
                      })}
                    </Text>
                  </View>
                </View>
              </Touchable>
            )}
          />
        </BottomSheet>
      </View>
    );
  }
}

const ServiceCard = props => (
  <View style={Styles.cardContainer}>
    <Text style={Styles.cardTitle}>{props.title}</Text>
    <View style={Styles.cardContent}>
      <View>
        {props.currentPlan.id === props.service.id &&
        props.currentPlan.id > 1 ? (
          <Text style={Styles.cardLabel}>{formatDate(props.validity)}</Text>
        ) : null}
        <Text style={Styles.cardLabel}>
          {I18n.t('form.label.service.order', {limit: props.max})}
        </Text>
        <Text style={Styles.cardLabel}>
          {I18n.t('form.label.service.space', {space: props.space})}
        </Text>
        <Text style={Styles.cardLabel}>
          {I18n.t('form.label.service.price', {price: props.price})}
        </Text>
      </View>
      {props.currentPlan.id === 1 && props.service.id === 1 ? (
        <View style={[Styles.cardBtn, Styles.cardBtnUse]}>
          <Text style={Styles.cardBtnLabel}>
            {I18n.t('form.label.service.current')}
          </Text>
        </View>
      ) : null}
      {props.currentPlan.id === 1 && props.service.id > 1 ? (
        <Touchable onPress={() => props.showModalUpgrade()}>
          <View style={Styles.cardBtn}>
            <Text style={Styles.cardBtnLabel}>
              {I18n.t('form.label.service.upgrade')}
            </Text>
          </View>
        </Touchable>
      ) : null}
      {props.currentPlan.id > 1 && props.currentPlan.id === props.service.id ? (
        <Touchable onPress={() => props.showModalAmend()}>
          <View style={[Styles.cardBtn, Styles.cardBtnUse]}>
            <Text style={Styles.cardBtnLabel}>
              {I18n.t('form.label.service.amend')}
            </Text>
          </View>
        </Touchable>
      ) : null}
      {props.currentPlan.id > 1 && props.currentPlan.id < props.service.id ? (
        <Touchable onPress={() => props.showModalUpgrade()}>
          <View style={[Styles.cardBtn, Styles.cardBtnUse]}>
            <Text style={Styles.cardBtnLabel}>
              {I18n.t('form.label.service.upgrade')}
            </Text>
          </View>
        </Touchable>
      ) : null}
    </View>
  </View>
);

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  serviceState: state.serviceState,
});

const mapDispatchToProps = dispatch => ({
  serviceActions: bindActionCreators(serviceActionCreator, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(ServiceScreen);

const Styles = StyleSheet.create({
  container: {
    // ...ThemeStyles.Color.background.white,
    // paddingHorizontal: getRealSize(15),
  },
  cardContainer: {
    justifyContent: 'center',
    backgroundColor: '#2E2F30',
    borderRadius: getRealSize(8),
    height: getRealSize(160),
    marginTop: getRealSize(15),
    marginHorizontal: getRealSize(15),
    paddingHorizontal: getRealSize(24),
  },
  cardTitle: {
    color: '#B08C59',
    fontSize: getRealSize(32),
    fontWeight: 'bold',
  },
  cardLabel: {
    color: 'white',
    fontSize: getRealSize(10),
    fontWeight: '400',
  },
  cardContent: {
    marginTop: getRealSize(18),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  cardBtn: {
    paddingHorizontal: getRealSize(12),
    paddingVertical: getRealSize(6),
    borderRadius: getRealSize(12),
    borderWidth: 1,
    borderColor: ThemeStyles.Color.primary.color,
    backgroundColor: ThemeStyles.Color.primary.color,
  },
  cardBtnUse: {
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: ThemeStyles.Color.transparent,
  },
  cardBtnLabel: {
    fontSize: getRealSize(10),
    fontWeight: 'bold',
    color: 'white',
  },
  sheetContainer: {
    borderTopColor: ThemeStyles.Color.line.color,
    borderTopWidth: StyleSheet.hairlineWidth,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 12,
    },
    shadowOpacity: 0.58,
    shadowRadius: 16.0,

    elevation: 24,
  },
  box: {
    marginHorizontal: getRealSize(15),
    borderRadius: getRealSize(4),
    borderWidth: getRealSize(1),
    borderColor: ThemeStyles.Color.primary.color,
    padding: getRealSize(12),
  },
  head: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  title: {
    flex: 1,
    fontSize: getRealSize(16),
    fontWeight: '400',
    color: '#333',
  },
  name: {
    width: getRealSize(72),
    textAlign: 'right',
    fontSize: getRealSize(16),
    fontWeight: '400',
    color: '#333',
  },
  content: {},
  label: {
    color: '#757575',
  },
});
